#!/usr/bin/env bash
# 以root身份运行
# 首先要先copy stack.sh到虚拟机上

## mount一些比较耗空间的目录
TMP_DEV=/dev/xvdd
IMAGE_DEV=/dev/xvde
BUCKET_DEV=/dev/xvdf
TMP_DIR=/tmp
IMAGE_DIR=/glance/images
BUCKET_DIR=/nova/buckets
chown -R stack:stack $TMP_DIR && chmod a+w -R $TMP_DIR && chmod o+t -R $TMP_DIR && mount $TMP_DEV $TMP_DIR
(mkdir $IMAGE_DIR && mkdir $BUCKET_DIR) || true
chown -R stack:stack $IMAGE_DIR && chmod 775 -R $IMAGE_DIR && mount $IMAGE_DEV $IMAGE_DIR
chown -R stack:stack $BUCKET_DIR && chmod 775 -R $BUCKET_DIR && mount $BUCKET_DEV $BUCKET_DIR
echo "$TMP_DEV                    $TMP_DIR                   ext3    defaults        0 0" >> /etc/fstab
echo "$IMAGE_DEV                   $IMAGE_DIR                   ext3    defaults        0 0" >> /etc/fstab
echo "$BUCKET_DEV                    $BUCKET_DIR                   ext3    defaults        0 0" >> /etc/fstab


## 修改glance-registry.conf和glance-api.conf配置文件
GLANCE_REGISTRY_FILE=/etc/glance/glance-registry.conf
GLANCE_API_FILE=/etc/glance/glance-api.conf
sed -i 's/^# log_file/log_file/g'  $GLANCE_REGISTRY_FILE
sed -i 's/^# log_file/log_file/g'  $GLANCE_API_FILE
sed -i '/^filesystem_store_datadir.*/{s|/opt/stack||g}' $GLANCE_REGISTRY_FILE
sed -i '/^filesystem_store_datadir.*/{s|/opt/stack||g}' $GLANCE_API_FILE


## 通过openstack-startguider的提示添加这些脚本
NOVA_USER=novaadmin
NOVA_PROJECT=proj
CREDS_DIR=/root/creds
# create a user with admin rights on nova
$NOVA_DIR/bin/nova-manage user admin $NOVA_USER
# create a project named proj
$NOVA_DIR/bin/nova-manage project create $NOVA_PROJECT $NOVA_USER
# Create a directory to download nova credentials and download the zip file
mkdir $CREDS_DIR || true
# Generate and save credentials for accessing/managing the nova cloud
$NOVA_DIR/bin/nova-manage project zipfile $NOVA_PROJECT $NOVA_USER $CREDS_DIR/novacreds.zip
# Navigate into the folder created and extract the files and change their ownership.
cd $CREDS_DIR && unzip novacreds.zip && chown stack:stack $CREDS_DIR -R
# In Diablo, by default novarc file contains EC2_ACCESS_KEY in a format that is not usable by euca-* commands. To fix this:
# 替换export EC2_ACCESS_KEY这行
EC2_ACCESS_KEY_LINE=`$NOVA_DIR/bin/nova-manage user exports $NOVA_USER | grep 'export EC2_ACCESS_KEY'`":$NOVA_PROJECT"
sed -i 's/^export EC2_ACCESS_KEY.*/'"$EC2_ACCESS_KEY_LINE"'/g' novarc
source novarc

# source eucarc
# 还是从dashboard上获取证书吧，不知道怎么获取OS_USERNAME和OS_TENANT_NAME两个变量
# source /opt/stack/devstack/eucarc

# add keypairs to run instance
euca-add-keypair mykey > mykey.priv
chmod 0600 mykey.priv
